package net.alan.modules.filter;

import net.alan.modules.cache.WebContextUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@WebFilter
public class SessionFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        /**
         * 验证用户是否登陆
         */
        String contextPath = req.getContextPath();
        String uri = req.getRequestURI();
        boolean isLogin = WebContextUtil.isLogin();
        boolean file = uri.contains(".");
        boolean swagger = uri.contains("swagger");
        boolean v2 = uri.contains("v2");
        if (!v2 && !swagger && !file && !isLogin && !(uri.indexOf("register") > 0 ||uri.indexOf("login") > 0 || uri.indexOf("index") > 0)) {
            resp.sendRedirect(contextPath + "/home/login");
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

}
